#!/usr/bin/python3
# -*- coding: utf-8 -*-

"""
# @version: v1.0
# @author : wlis
# @Email : 19688513@qq.com
# @Project : g-carbon-bio
# @File : trade_date_manager.py
# @Software: PyCharm
# @time: 2025/3/18 17:32
# @description : 获取历史交易日期数据  调用接口 ak.tool_trade_date_hist_sina()
"""

import akshare as ak
import sqlite3
import os
import logging
from datetime import datetime, date
from path_helper import PathManager  # 引入路径管理器

# 配置日志，设置日志级别和格式
logging.basicConfig(level=logging.INFO, format='%(asctime)s - %(levelname)s - %(message)s')

class TradeDateManager:
    def __init__(self, db_name='trade_dates.db'):
        """
        初始化 TradeDateManager 类

        Args:
            db_name (str): 存储交易日期数据的 SQLite 数据库名称，默认为 'trade_dates.db'
        """
        pm = PathManager()  # 创建路径管理器实例
        self.db_name = pm.get_database_path(db_name)  # 获取数据库的完整路径
        self.create_database()

    def create_database(self):
        """创建 SQLite 数据库和交易日期表"""
        if not os.path.exists(self.db_name):
            conn = sqlite3.connect(self.db_name)
            cursor = conn.cursor()
            cursor.execute('''
                CREATE TABLE IF NOT EXISTS trade_dates (
                    trade_date TEXT PRIMARY KEY
                )
            ''')
            conn.commit()
            conn.close()
            logging.info(f"数据库 {self.db_name} 已创建。")
        else:
            logging.info(f"数据库 {self.db_name} 已存在，不会重新创建。")

    def fetch_and_store_trade_dates(self):
        """从 Akshare 获取交易日期数据并存储到 SQLite 数据库"""
        tool_trade_date_hist_sina_df = ak.tool_trade_date_hist_sina()
        conn = sqlite3.connect(self.db_name)
        cursor = conn.cursor()
        for index, row in tool_trade_date_hist_sina_df.iterrows():
            cursor.execute('''
                INSERT OR IGNORE INTO trade_dates (trade_date) VALUES (?)
            ''', (row['trade_date'],))
        conn.commit()
        conn.close()
        logging.info("交易日期数据已成功存储到数据库。")

    def read_trade_dates(self):
        """从 SQLite 数据库读取交易日期数据，并返回日期列表"""
        conn = sqlite3.connect(self.db_name)
        cursor = conn.cursor()
        cursor.execute("SELECT trade_date FROM trade_dates")
        rows = cursor.fetchall()
        conn.close()
        return [row[0] for row in rows]

    def is_tool_trading_day(self, date):
        """判断给定日期是否为工具交易日"""
        if date is None:
            raise ValueError("日期不能为空")
        tool_days = self.read_trade_dates()
        return date.strftime('%Y-%m-%d') in tool_days

    def get_start_end_date(self, trade_date: str, y_day: int):
        """根据给定的交易日期和天数，计算起始日期和结束日期"""
        trade_dates = self.read_trade_dates()
        if trade_dates and trade_date in trade_dates:
            index = trade_dates.index(trade_date)
            start_index = max(0, index - y_day)
            end_index = index
            start_date = trade_dates[start_index]
            end_date = trade_dates[end_index]
            return start_date, end_date
        else:
            raise ValueError("交易日期不在数据库中")

    def get_offset_trade_dates(self, trade_date, offset_days: int):
        """获取给定交易日期的偏移交易日期"""
        if isinstance(trade_date, date):
            trade_date_str = trade_date.strftime('%Y-%m-%d')
        elif isinstance(trade_date, str):
            trade_date_str = trade_date
        else:
            raise ValueError("交易日期必须是 datetime.date 或字符串格式")

        tool_days = self.read_trade_dates()
        if trade_date_str in tool_days:
            index = tool_days.index(trade_date_str)
            previous_index = index - offset_days
            next_index = index
            min_trade_date = '1990-12-19'  # 假设的最早交易日期

            previous_trade_date = tool_days[previous_index] if previous_index >= 0 else min_trade_date
            next_trade_date = tool_days[next_index] if next_index < len(tool_days) else None

            return previous_trade_date, next_trade_date
        else:
            raise ValueError("给定的交易日期不在交易日期列表中")

    def delete_trade_date(self, trade_date: str):
        """删除指定的交易日期"""
        conn = sqlite3.connect(self.db_name)
        cursor = conn.cursor()
        cursor.execute('''
            DELETE FROM trade_dates WHERE trade_date = ?
        ''', (trade_date,))
        conn.commit()
        conn.close()
        logging.info(f"交易日期 {trade_date} 已被删除。")

    def update_trade_date(self, old_date: str, new_date: str):
        """更新指定的交易日期"""
        conn = sqlite3.connect(self.db_name)
        cursor = conn.cursor()
        cursor.execute('''
            UPDATE trade_dates SET trade_date = ? WHERE trade_date = ?
        ''', (new_date, old_date))
        conn.commit()
        conn.close()
        logging.info(f"交易日期 {old_date} 已更新为 {new_date}。")

    def delete_database(self) -> None:
        """删除数据库文件"""
        try:
            if os.path.exists(self.db_name):
                os.remove(self.db_name)
                logging.info(f"数据库 {self.db_name} 已成功删除")
            else:
                logging.warning(f"数据库 {self.db_name} 不存在，无法删除")
        except Exception as e:
            logging.error(f"删除数据库失败: {e}")


# 示例用法
if __name__ == "__main__":
    trade_calendar = TradeDateManager()

    # 获取并存储交易日期数据
    trade_calendar.fetch_and_store_trade_dates()

    # 获取交易日期列表
    trade_dates = trade_calendar.read_trade_dates()
    print("交易日期列表:", trade_dates)

    # 判断某一天是否为交易日
    test_date = datetime(2023, 10, 10)
    is_trading_day = trade_calendar.is_tool_trading_day(test_date)
    print(f"{test_date.strftime('%Y-%m-%d')} 是否为交易日: {is_trading_day}")

    # 获取偏移交易日期
    offset_days = 1
    input_date = "2023-10-25"
    try:
        previous_trade_date, next_trade_date = trade_calendar.get_offset_trade_dates(input_date, offset_days)
        print(f"输入日期: {input_date}")
        print(f"前一个交易日期: {previous_trade_date}")
        print(f"后一个交易日期: {next_trade_date}")
    except ValueError as e:
        print(e)

    # 获取起始日期和结束日期
    try:
        start_date, end_date = trade_calendar.get_start_end_date("2023-10-25", 5)
        print(f"起始日期: {start_date}, 结束日期: {end_date}")
    except ValueError as e:
        print(e)

    # 示例：删除指定的交易日期
    # trade_calendar.delete_trade_date("2023-10-25")
    # print("删除交易日期 2023-10-25")
    #
    # 示例：更新交易日期
    # trade_calendar.update_trade_date("2023-10-26", "2023-10-27")
    # print("更新交易日期 2023-10-26 为 2023-10-27")
